//
//  AppDelegate.m
//  FitTime
//
//  Created by 赵建平 on 16/3/30.
//  Copyright © 2016年 赵建平. All rights reserved.
//

#import "AppDelegate.h"
#import "MainViewController.h"
#import "ClockViewController.h"
#import "SportViewController.h"
#import "MineViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
#import <iflyMSC/iflyMSC.h>
#import "ZHXIntroductionViewController.h"

static SystemSoundID audio_queue = 0;

@interface AppDelegate ()

@property (nonatomic, retain) UITabBarController *tabBar;
@property (nonatomic, retain) NSTimer *vibrate; //震动
@property (nonatomic, retain) NSTimer *musicPlay; //音乐
@property (nonatomic, retain) NSArray *musicArr;
@property (nonatomic, retain) AVAudioPlayer *player;// 后台播放器

@end

@implementation AppDelegate


void playFinished(SystemSoundID  ssID, void* clientData)
{
    AudioServicesPlaySystemSound((SystemSoundID)audio_queue);
}

- (void)configFlySpeech
{
    
    [IFlySpeechUtility createUtility:[NSString stringWithFormat:@"appid=%@,timeout=%@",@"570b919b",@"20000"]];
    
    [IFlySetting setLogFile:LVL_NONE];
    [IFlySetting showLogcat:NO];
    // 设置语音合成的参数
    [[IFlySpeechSynthesizer sharedInstance] setParameter:@"50" forKey:[IFlySpeechConstant SPEED]]; //合成的语速,取值范围 0~100
    [[IFlySpeechSynthesizer sharedInstance] setParameter:@"50" forKey:[IFlySpeechConstant VOLUME]]; //合成的音量;取值范围 0~100
    // 发音人
    [[IFlySpeechSynthesizer sharedInstance] setParameter:@"vixr" forKey:[IFlySpeechConstant VOICE_NAME]];
    // 音频采样率,目前支持的采样率有 16000 和 8000;
    [[IFlySpeechSynthesizer sharedInstance] setParameter:@"8000" forKey:[IFlySpeechConstant SAMPLE_RATE]];
    // 当你再不需要保存音频时，请在必要的地方加上这行。
    [[IFlySpeechSynthesizer sharedInstance] setParameter:nil forKey:[IFlySpeechConstant TTS_AUDIO_PATH]];
    
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.musicArr = @[@"Airship", @"Alarm Close", @"Alien Metron", @"Astronaut", @"BoDeSa", @"Calculator", @"Falling Stone", @"Firefly", @"Lantern Star", @"Lemon Port",@"Milky Way", @"Mineral", @"Mushrooms Villain", @"Nothing", @"Rich Base", @"Rocket Launch", @"Satellite", @"Stars", @"Time Tunnel", @"Time Machine", @"UFO", @"Unknown Creature", @"Wormhole"];
        
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.window makeKeyAndVisible];
    
    
    [self configFlySpeech];
    
    //   标签：视频
    MainViewController *videoVC = [[MainViewController alloc] init];
    UINavigationController *navVideo = [[UINavigationController alloc] initWithRootViewController:videoVC];
    navVideo.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"极限健身" image:[UIImage imageNamed:@"哑铃1"] selectedImage:[[UIImage imageNamed:@"哑铃2"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]] ;
    //   标签：闹钟
    ClockViewController *clockVC = [[ClockViewController alloc] init];
    clockVC.title = @"斑斓时刻";
    UINavigationController *navClock = [[UINavigationController alloc] initWithRootViewController:clockVC];
    navClock.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"斑斓时刻" image:[UIImage imageNamed:@"闹钟1"] selectedImage:[[UIImage imageNamed:@"闹钟2"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    //   标签：运动
    SportViewController *sportVC = [[SportViewController alloc] init];
    sportVC.title = @"运动旅程";
    UINavigationController *navSport = [[UINavigationController alloc] initWithRootViewController:sportVC];
    navSport.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"运动旅程" image:[UIImage imageNamed:@"运动1"] selectedImage:[[UIImage imageNamed:@"运动2"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    //    标签：我的
    MineViewController *mineVC = [[MineViewController alloc] init];
    mineVC.title = @"我的设置";
    UINavigationController *navMine = [[UINavigationController alloc] initWithRootViewController:mineVC];
    navMine.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"我的设置" image:[UIImage imageNamed:@"我1"] selectedImage:[[UIImage imageNamed:@"我2"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    //    创建TabBar
    self.tabBar = [[UITabBarController alloc] init];
    self.tabBar.viewControllers = @[navVideo, navClock, navSport, navMine];
    self.tabBar.tabBar.barTintColor = [UIColor colorWithRed:0.939 green:0.726 blue:0.482 alpha:1.000];
    self.tabBar.tabBar.tintColor = [UIColor colorWithWhite:0.250 alpha:1.000];
    //    引导页
    NSUserDefaults *leadPages = [NSUserDefaults standardUserDefaults];
    if (![leadPages objectForKey:@"firstInstall112"]) {
        [leadPages setObject:@"YES" forKey:@"firstInstall112"];
        ZHXIntroductionViewController *zhxVC = [[ZHXIntroductionViewController alloc] init];
        
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        [center addObserver:self selector:@selector(buttonAction:) name:@"changeRootVC" object:nil];
        
        self.window.rootViewController = zhxVC;
    } else {
        self.window.rootViewController = _tabBar;
    }
    
    //处理iOS8本地推送不能收到
    float sysVersion=[[UIDevice currentDevice]systemVersion].floatValue;
    if (sysVersion>=8.0) {
        UIUserNotificationType type=UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound;
        UIUserNotificationSettings *setting=[UIUserNotificationSettings settingsForTypes:type categories:nil];
        [[UIApplication sharedApplication]registerUserNotificationSettings:setting];
    } else {
        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
    }

    return YES;
}

- (void)buttonAction:(UIButton *)sender {
    self.window.rootViewController = _tabBar;
}

#pragma mark 远程推送
//#ifdef __IPHONE_8_0
//- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings{
//    [application registerForRemoteNotifications];
//}
//#endif
//
//#pragma mark 注册Token值
//- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
//    NSLog(@"deviceToken:%@",deviceToken);
//}
//
//#pragma mark 程序正在使用或者退出的状态下
//- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
//    
//    NSLog(@"远程推送");
//    
//}

#pragma mark 程序正在前台的状态下
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
    
    NSLog(@"走你");
    
    if (notification) {
        
        UIAlertView *alartView = [[UIAlertView alloc]initWithTitle:nil message:@"闹钟响了!!!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        
        self.vibrate = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(Vibrate) userInfo:nil repeats:YES];

        NSString *string = notification.userInfo.allValues[0];
        
        NSInteger musicNumber = [string substringWithRange:NSMakeRange(string.length - 2, 2)].integerValue;
        
        NSString *path = [[NSBundle mainBundle] pathForResource:self.musicArr[musicNumber] ofType:@"mp3"];
        
        if (path) {
            //注册声音到系统
            NSURL *soundURL =[NSURL fileURLWithPath:path];
            OSStatus err = AudioServicesCreateSystemSoundID((__bridge CFURLRef)soundURL, &audio_queue);
            if(err!= kAudioServicesNoError){
                NSLog(@"Could not load %@,error code:%d",soundURL,err);
            }
        }
        
        AudioServicesPlaySystemSound((SystemSoundID)audio_queue); //开始播放声音
        
        AudioServicesAddSystemSoundCompletion(audio_queue, NULL, NULL, &playFinished, (__bridge void *)(self));
        
        [alartView show];
        
    }
    
}

#pragma mark - 连续震动
- (void)Vibrate {
    
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);   //让手机震动
    
}

#pragma mark 点击确定取消震动音乐
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    [self.vibrate invalidate];
    AudioServicesDisposeSystemSoundID((SystemSoundID)audio_queue);
    AudioServicesRemoveSystemSoundCompletion((SystemSoundID)audio_queue);
    [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
    
}

//#pragma mark 后台运行（伪装后台）
//- (void)applicationDidEnterBackground:(UIApplication *)application{
// 
//    NSLog(@"后台开启");
//    
//    [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
//    
//    [NSTimer scheduledTimerWithTimeInterval:60.0f target:self selector:@selector(tik) userInfo:nil repeats:YES];
//
//    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
//    
//    [[AVAudioSession sharedInstance] setActive: YES error: nil];
//
//}
//
//- (void)tik{
//    
//    NSLog(@"持续后台");
//    
//    if ([[UIApplication sharedApplication] backgroundTimeRemaining] < 61.0) {
//        
//        [self playAudio];//播放空音乐
//        
//        [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
//        
//    }
//    
//    
//}
//
//- (void)playAudio
//{
//    if ([_player isPlaying])
//    {
//        [_player stop];
//    }
//    [_player play];
//}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
